package com.glasses.service.imp;

import com.alibaba.fastjson.JSONObject;
import com.glasses.dao.*;
import com.glasses.entity.Address;
import com.glasses.entity.Commodity;
import com.glasses.entity.Order;
import com.glasses.entity.User;
import com.glasses.orm.base.Ex.BaseServiceEx;
import com.glasses.orm.dictionary.ExpressStatus;
import com.glasses.orm.dictionary.Status;
import com.glasses.orm.utils.WxUtils;
import com.glasses.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ashin on 2018/1/24.
 */
@Service
public class OrderServiceImp extends BaseServiceEx implements OrderService {

    @Autowired
    OrderDao orderDao;

    @Autowired
    CommodityDao commodityDao;

    @Autowired
    IndentDao indentDao;

    @Autowired
    UserDao userDao;

    @Autowired
    WxUtils wxUtils;

    @Autowired
    AddressDao addressDao;

    @Override
    public void init() {
        super.init(orderDao);
    }

    @Transactional
    @Override
    public JSONObject cancelOrder(Map map) throws Exception {
        Order order = orderDao.selectp(map);
        int ret = orderDao.deleteOrder(map);
        indentDao.deleteIndent(map);
        if (ret == -1)
            return this.codeMess(eCode, "删除失败");
        Map orderMap = new HashMap();
        orderMap.put("openId", order.getOpenId());
        orderMap.put("pageSize", map.get("pageSize"));
        orderMap.put("pageNo", map.get("pageNo"));
        return this.pagequery(orderMap);
    }

    @Transactional
    @Override
    public JSONObject addOrder(Map map) throws Exception {
        Map commodityMap = new HashMap();
        commodityMap.put("id", map.get("commodityId"));
        Commodity commodity = commodityDao.selectp(commodityMap);
        int ret = -1;
        int amount = toInt(map.get("amount").toString());
        Map userMap = new HashMap();
        userMap.put("openId", map.get("openId"));
        if (null != map.get("isIndentCost") && "1".equals(map.get("isIndentCost").toString())) {
            User _user = userDao.getMyIndent(map);
            //更新积分表
            Map indentMap = new HashMap();
            indentMap.put("openId", map.get("openId"));
            indentMap.put("indent", 0d - _user.getTotalIndent());
            indentMap.put("title", commodity.getTitle());
            ret = indentDao.insertp(indentMap);
        }
        map.put("backIndent", commodity.getBackIndent() * amount);
        map.put("orderId", orderId());
        map.put("status", Integer.parseInt(String.valueOf(Status.待付款)));
        map.put("amount", amount);
        ret = orderDao.insertp(map);

        if (ret == -1) {
            return this.codeMess(eCode, "支付失败");
        }
        return this.codeMess(sCode, "支付成功");
    }

    @Transactional
    @Override
    public JSONObject pay(Map map, HttpServletRequest request) throws Exception {

        map.put("openId", map.get("openId"));
        map.put("spbill_create_ip", getIpAddr(request));
        //查询商品信息
        Map CommodityMap = new HashMap<>();
        CommodityMap.put("id", map.get("commodityId"));
        Commodity commodity = commodityDao.selectp(CommodityMap);
        /*
         * 判断商品是否存在
         */
        if (commodity == null) {
            return this.codeMess(eCode, "该商品已经下架,请返回首页重新选择");
        }

        /*
         * 判断地址是否存在
         */
        String addrInfo;
        if (map.get("addressId") == null) {
            return this.codeMess(eCode, "请先选择地址");
        } else {
            Map addressMap = new HashMap();
            addressMap.put("id", map.get("addressId"));
            Address address = addressDao.selectp(addressMap);
            if (address == null) {
                return this.codeMess(eCode, "地址不存在,请重新选择");
            }
            addrInfo = address.getName() + " " + address.getPhone() + " " + address.getAddress() + " " + address.getAddressInfo();
        }

        String orderId = orderId();
        //是否勾选积分抵扣
        if (null != map.get("costIndent") && toInt(map.get("costIndent").toString()) > 0) {
            User user = userDao.getMyIndent(map);
            int totalIndent = user.getTotalIndent();
            //判断当前我的积分是否大于消费积分
            if (totalIndent - toInt(map.get("costIndent").toString()) < 0) {
                return this.codeMess(eCode, "抱歉，您的积分不足，刷新积分重新查看");
            }
            //更新积分表
            Map indentMap = new HashMap();
            indentMap.put("openId", map.get("openId"));
            indentMap.put("indent", 0d - toInt(map.get("costIndent").toString()));
            indentMap.put("title", commodity.getTitle());
            indentMap.put("orderId", orderId);
            indentDao.insertp(indentMap);
        }
        map.put("total_fee", toInt(map.get("totalCost").toString()) * 100);
        map.put("orderId", orderId);
        JSONObject wxPayJSON = wxUtils.wxPay(map);
        if (wxPayJSON.getInteger("code") == sCode) {
            //TODO 新增订单以及商品信息

            Map orderMap = new HashMap();
            orderMap.put("orderId", orderId);
            orderMap.put("openId", map.get("openId"));
            orderMap.put("commodityId", map.get("commodityId"));
            orderMap.put("status", String.valueOf(Status.待付款));
            orderMap.put("backIndent", commodity.getBackIndent());
            orderMap.put("expressStatus", String.valueOf(ExpressStatus.待发货));
            orderMap.put("amount", 1); //暂时不支持多件
            orderMap.put("currentCost", map.get("totalCost").toString());
            orderMap.put("costIndent", map.get("costIndent").toString());
            orderMap.put("extra", map.get("extra"));
            orderMap.put("commodityExtra", map.get("commodityExtra"));
            orderMap.put("addrInfo", addrInfo);

            orderDao.insertp(orderMap);
        }
        //创建支付订单
        return wxPayJSON;
    }

    @Override
    public JSONObject getOrderCountStatus(Map map) throws Exception {
        Map countStatusMap = orderDao.getOrderCountStatus(map);
        return this.codeData(countStatusMap);
    }

    @Override
    public JSONObject getCommodityStatusCount(Map map) throws Exception {
        Map countStatusMap = orderDao.getCommodityStatusCount(map);
        return this.codeData(countStatusMap);
    }

    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
     *
     * @return ip
     */
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.contains(",")) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
